<template>
  <a-modal
    :open="open"
    width="640px"
    :title="rowData?.id ? '修改系统通知' : '新增系统通知'"
    centered
    :ok-button-props="{ disabled: rowData?.status === 1 ? true : !isCompleted }"
    ok-text="保存"
    @ok="onOk"
    @cancel="onCancel"
  >
    <a-form :model="formState" class="form-style-flex">
      <a-form-item label="通知标题" class="w-full" v-bind="validateInfos.title">
        <a-input v-model:value="formState.title" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="通知内容" class="w-full" v-bind="validateInfos.content">
        <a-textarea v-model:value="formState.content" :rows="6" placeholder="请输入" />
      </a-form-item>
      <a-form-item label="通知类别" class="w-full" v-bind="validateInfos.noticeType">
        <a-select v-model:value="formState.noticeType" placeholder="请选择" @change="getDepartmentTreeList">
          <a-select-option :value="0">全院</a-select-option>
          <a-select-option :value="1">科室</a-select-option>
          <a-select-option :value="2">部门</a-select-option>
          <a-select-option :value="3">个人</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="通知对象" class="w-full" v-bind="validateInfos.relationId">
        <a-tree-select
          v-if="formState.noticeType !== 0 && formState.noticeType !== 3"
          v-model:value="formState.relationId"
          show-search
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          placeholder="请选择"
          allow-clear
          max-tag-count="responsive"
          tree-default-expand-all
          :tree-data="departmentTreeList"
          tree-node-filter-prop="label"
          :tree-checkable="true"
          :show-checked-strategy="SHOW_PARENT"
        />
        <a-select
          v-else-if="formState.noticeType === 3"
          v-model:value="formState.relationId"
          mode="multiple"
          show-search
          max-tag-count="responsive"
          placeholder="请选择"
          :options="departmentTreeList"
        />
        <a-select v-else-if="formState.noticeType === 0" v-model:value="formState.relationIdQY" placeholder="请选择" @select="onSelectRelationId">
          <a-select-option :value="0">全院</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="生效日期" class="w-1/2">
        <a-date-picker v-model:value="formState.effectiveDate" :disabled-date="disabledDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
      </a-form-item>
      <a-form-item label="失效日期" class="w-1/2">
        <a-date-picker v-model:value="formState.expirationDate" :disabled-date="disabledEndDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import { TreeSelect } from 'ant-design-vue'
import { post } from '@/utils/request'

const SHOW_PARENT = TreeSelect.SHOW_PARENT

// const relationIdChecked = ref([])
const relationIdTree = ref([])
const emit = defineEmits(['update:open', 'ok'])
const props = defineProps({
  open: {
    type: Boolean,
    default: false
  },
  rowData: {
    type: Object,
    default: () => ({})
  }
})
const departmentUrl = ref('')
const departmentFormData = ref({})
const departmentTreeList = ref([])
const formState = ref({
  noticeType: 0,
  title: '',
  content: '',
  relationId: [],
  effectiveDate: dayjs().format('YYYY-MM-DD'),
  expirationDate: dayjs(new Date().setDate(new Date().getDate() + 7)).format('YYYY-MM-DD'),
  id: ''
})
const rulesState = ref({
  noticeType: [{ required: true, message: '请选择通知类别' }],
  title: [{ required: true, message: '请输入通知标题' }],
  content: [{ required: true, message: '请输通知内容' }],
  relationId: [{ required: true, message: '请选择通知对象' }]
})
const { isCompleted, resetFields, validate, validateInfos } = useForm(formState, rulesState)

const onSelectRelationId = () => {
  formState.value.relationId = ['0']
}

const getDepartmentTreeList = async (val) => {
  if (val !== undefined) formState.value.relationId = []
  if (formState.value.noticeType === 1) {
    departmentUrl.value = '/operation/opex/getDeptInfoList'
    departmentFormData.value = {}
  } else if (formState.value.noticeType === 2) {
    departmentUrl.value = '/operation/opex/getSystemDeptList'
  } else if (formState.value.noticeType === 3) {
    departmentUrl.value = '/operation/opex/getEmpInfoList'
    departmentFormData.value = {
      status: 0,
      pageNum: 1,
      pageSize: 999
    }
  } else {
    return false
  }
  const { code, data } = await post(departmentUrl.value, departmentFormData.value)
  if (code !== 0) return
  departmentTreeList.value = convertToTreeSelectData(data)
  relationIdTree.value = departmentTreeList.value
}

//解析树结构
const convertToTreeSelectData = (data) => {
  const result = []
  if (formState.value.noticeType === 3)
    return data.map((item) => {
      return {
        label: item.empName,
        value: item.empId
      }
    })
  data.forEach((item) => {
    const newItem = ref({})

    if (formState.value.noticeType === 1) {
      //科室
      newItem.value = {
        label: item.ksmc + (item.children?.length ? ` (${item.children?.length})` : ''),
        value: item.ksdm,
        deptName: item.ksmc
      }
    } else if (formState.value.noticeType === 2) {
      //部门
      newItem.value = {
        label: item.deptName + (item.children?.length ? ` (${item.children?.length})` : ''),
        value: item.deptCode,
        deptName: item.deptName
      }
    }
    if (item.children && item.children.length > 0) {
      newItem.value.children = convertToTreeSelectData(item.children)
    }
    result.push(newItem.value)
  })

  return result
}
const disabledDate = (current) => {
  // 禁用今天之前的日期
  return current && current < new Date()
}
const disabledEndDate = (current) => {
  // 禁用今天之前的日期
  return (current && current < new Date(formState.value.effectiveDate)) || current < new Date()
}
watch(
  () => props.open,
  (val) => {
    if (val) {
      if (props.rowData?.id) {
        formState.value = { ...props.rowData } || {}
        if (props.rowData.relationIdQY === 0) {
          formState.value.relationId = ['0']
        }
      } else {
        formState.value = {}
      }
      getDepartmentTreeList()
    }
  }
)
const onCancel = () => {
  emit('update:open', false)
  resetFields()
}
const onOk = async () => {
  await validate()
  if (formState.value.noticeType === 0) formState.value.relationId = []
  const { code, msg } = await post('/operation/opex/doSaveSystemNotice', formState.value)
  if (code !== 0) return message.error(msg)
  message.success('保存成功')
  emit('ok')
  onCancel()
}
</script>
